import { login, logout } from "@/api/public/auth";
import { getUserInfo } from "@/api/public/personal";
import { loadRoutes } from "@/router/helper";

/**
 * 用户State
 */
export interface UserState {
  // token
  token: string;
  // 用户信息
  userInfo: object;
  // 角色
  roles: string[];
  // 权限
  permissions: string[];
  // 菜单
  menu: string[];
}

export const useUserStore = defineStore("userStore", {
  state: (): UserState => ({
    token: "",
    userInfo: {},
    menu: [],
    roles: [],
    permissions: []
  }),
  actions: {
    /**
     * 登录
     * @param userinfo
     */
    login(userinfo) {
      return new Promise<any>((resolve, reject) => {
        login(userinfo)
          .then(res => {
            const data = res.data;
            this.token = data.token;
            this.menu = data.menu;
            loadRoutes();
            resolve(data);
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    /**
     * 注销登录
     */
    logout() {
      return new Promise<void>((resolve, reject) => {
        logout()
          .then(() => {
            this.token = "";
            this.menu = [];
            this.userInfo = {};
            this.roles = [];
            this.permissions = [];

            const appStore = useAppStore();
            appStore.setHeaderMenuSelectedKey(1);
            appStore.setSidebarMenuOpenKeys(["11", "12"]);
            appStore.setSidebarMenuSelectedKeys(["111"]);

            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    /**
     * 获取用户信息
     */
    getUserInfo() {
      return new Promise<any>((resolve, reject) => {
        getUserInfo()
          .then(res => {
            const data = res.data;
            this.roles = data.roles;
            this.permissions = data.permissions;
            delete data.roles;
            delete data.permissions;
            this.userInfo = data;
            resolve(data);
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  },
  persist: {
    enabled: true
  }
});
